import router, {constantRoutes} from '@/router'
import store from '@/store'

function hasPermission(roles, route) {
    if (route.meta && route.meta.roles) {
        return roles.some(role => route.meta.roles.includes(role))
    } else {
        return true
    }
}

/**
 * 后台查询的菜单数据拼装成路由格式的数据
 * @param routes (resolve: any) => require([`@/views/${view}.vue`], resolve)
 */
export function generaMenu(routes, data) {
    data.forEach(item => {
        if (item.类型 != '2') {
            const menu = {
                id: item.id,
                // 路由的路径
                path: item.链接地址,
                // 路由名
                name: item.链接地址,
                pageName: item.名称,
                // 路由所在组件
                // component: import('@/' + item.组件路径 + '.vue'),
                hidden: item.是否隐藏,
                icon: item.图标,   // 菜单图标
                meta: {
                    title: item.名称,
                    roles: item.子权限?.map(item => item.名称) || [],
                },
                // 路由的子路由
                children: []
            }

            if (item.子权限 && item.类型 == '0') {
                generaMenu(menu.children, item.子权限)
            } else {
                delete menu.children
            }
            routes.push(menu)
        }
    })
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
    const res = []

    routes.forEach(route => {
        const tmp = {...route}
        if (hasPermission(roles, tmp)) {
            if (tmp.children) {
                tmp.children = filterAsyncRoutes(tmp.children, roles)
            }
            res.push(tmp)
        }
    })

    return res
}

const state = {
    routes: window.localStorage.getItem('routes') ? JSON.parse(window.localStorage.getItem('routes')) : [],
    convertRoutes: window.localStorage.getItem('convertRoutes') ? JSON.parse(window.localStorage.getItem('convertRoutes')) : []
}

const mutations = {
    SET_ROUTES: (state, routes) => {
        state.routes = routes
        window.localStorage.setItem('routes', JSON.stringify(routes))
    },
    CONVERT_ROUTES: (state, routes) => {
        //将路由数据转换成一维数组
        let arr = []

        function convertRoutes(routes) {
            routes.forEach(item => {
                arr.push({...item, roles: item.meta.roles})
                if (item.children) {
                    convertRoutes(item.children)
                }
            })
        }

        convertRoutes(routes)
        state.convertRoutes = arr
        window.localStorage.setItem('convertRoutes', JSON.stringify(arr))
    }
}

const actions = {
    generateRoutes({commit}, loadMenuData = []) {
        return new Promise(resolve => {
            let roles = store.getters['global/roles']
            // const tempAsyncRoutes = Object.assign([], constantRoutes)
            const tempAsyncRoutes = []
            generaMenu(tempAsyncRoutes, loadMenuData)
            // let accessedRoutes
            // if (roles.includes('admin')) {
            //     accessedRoutes = tempAsyncRoutes || []
            // } else {
            // accessedRoutes = filterAsyncRoutes(tempAsyncRoutes, roles)
            // }
            commit('SET_ROUTES', tempAsyncRoutes)
            commit('CONVERT_ROUTES', tempAsyncRoutes)
            router.addRoutes(tempAsyncRoutes)
            resolve(tempAsyncRoutes)
        })
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}

